<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/6/16
 * Time: 21:00
 */
namespace Pay\Controller;

use Common\Common\Api\Order;
use Common\Common\Api\Ordermember;
use Common\Common\Api\Redis\Channel;
use Common\Common\Api\Redis\Product;

/**
 * Class ManyiController
 * @package Pay\Controller
 * 菲游
 */
class FeiyouController extends PayController{
    protected $config;
    protected $class;
    public function __construct(){
        parent::__construct();
        $classes = explode("\\",__CLASS__);
        $class = end($classes);
        $this->class = substr($class, 0, stripos($class, "Controller"));
    }



    // 获取编码后的字符
    public function doSign($t,$secretKey,$data){
        $string = json_encode($data);
        $str =$t."&".$secretKey."&".$string;
        $rs =md5($str);
        return $rs;
    }

    private function _microtime13(){
        return substr(str_replace(".","",strval(microtime(TRUE))), 0, 13) ;
    }

    public function get_last_rs($array){
        $t = $this->_microtime13();
        $data = array(
            't' => $t,
            'appKey' => $this->config['appsecret'],
            'sign' => $this->doSign($t, $this->config['signkey'], $array),
            'data' => json_encode($array),
            'version' => 2.0
        );

        $result = $this->httpRequest($this->config['gateway'].'/com.bxw.pay.mtop.OpenApi.preOrder/v1',$data);

        return $result;
    }

    // curl交互获取json数据
    public function httpRequest($sUrl, $aData){
        // 开启curl扩展模块  extension=php_curl.dll

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_URL, $sUrl);
        curl_setopt($ch, CURLOPT_POSTFIELDS,http_build_query($aData));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        /* curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json; charset=utf-8',
            'Content-Length: ' . strlen($aData)
        )
            ); */
        $response =urldecode(curl_exec($ch));
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        return $response;

    }


    // 回调参数校验
    // data 去除sign的参数
    // secretKey key
    public function callbackDosign($data, $secretKey){
        ksort($data);
        $str = $secretKey;
        foreach($data as $name=>$value)
        {
            $str = $str."&".$name."=".$value;
        }
        return md5($str);
    }

    ///


    public function pay($array){
        $this->config = Channel::getInstance()->getById($array['channel']);

        if(!$this->config){
            $this->showmessage('通道错误!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $product = Product::getInstance()->getById(I("request.pay_bankcode",0,"intval"));

        if(!$product){
            $this->showmessage('未找到支付产品!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $parameter = array(
            'code' => $this->config['code'], // 通道名称
            'title' => $this->config['title'],
            'exchange' => 1, // 金额比例
            'gateway' => $this->config['gateway'],
            'orderid' => createOrderId(),
            'out_trade_id' => I("request.pay_orderid"),
            'body' => 'pay',
            'channel'=>$array
        );

        $return = $this->orderadd( $parameter );

        switch($this->config['paytype']) {
            case 1:
            case 2:
                $bankcode = 'STARPOS_WECHAT';
                break;
            case 3:
            case 4:
                $bankcode = 'STARPOS_ALIPAY';
                break;
            default:
                $this->showmessage('暂不支持此支付方式!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $attrJson =[
            'code' => 'wanglianfu', // 通道名称
        ];

        $dataJson = array(
            "amount" => $return['amount'], // 交易金额
            "tradeName" => $this->config['title'],  // 商品名称
            "account" => $this->config['mch_id'],  // 商户账号
            "attrJson" => json_encode($attrJson,320), // 附加参数
            "notifyUrl" => $return['notifyurl'], // 回调通知路径
            "extendTradeNo" => $return['orderid'],//平台订单号
            "channelCode" => $bankcode //渠道编码
        );

        $result = json_decode($this->get_last_rs($dataJson),true);

        $code = $result['data']['h5PayUrl'] ? $result['data']['h5PayUrl'] : $result['data']['aliPayUrl'] ? $result['data']['aliPayUrl'] : "";

        if(!$code){
            if($result['msg']){
                $this->showmessage($result['msg'],['code'=>C("THIRDCODES.".$this->class)]);
            }

            $this->showmessage("获取支付链接失败",['code'=>C("THIRDCODES.".$this->class)]);
        }


        $ismobile = isMobile();

        $paytype = transArr( C("PAYTYPES"), "id");

        $this->assign("wap_url", $code);
        $this->assign("title", $paytype[$this->config['paytype']]);
        $this->assign("return", $return);
        $this->assign("imgurl", C("website.DOMAIN")."/Pay_Qrcode_getCode?type=2&data=".base64_encode($code));
        switch($this->config['paytype']){
            //微信
            case 1:
                header("Location:{$code}");
                break;
            //支付宝扫码
            case 3:
                //支付宝H5
            case 4:
                if($ismobile){
                    header("Location:{$code}");
                }else{
                    $this->display("WeiXin/alipay");
                }
                break;
            default:
                $this->display("WeiXin/Pay");
        }
    }

    //通知
    public function notifyurl(){
        //$this->debug_callback();
        $p = I("post.");

        if(empty($p)){
            echo "wrong"; exit;
        }

        $arr = $p;

        $p['attach'] = htmlspecialchars_decode($p['attach']);
        $sign = $p['sign'];

        //获取订单信息
        $orderid = $p['extendTradeNo'];

        $find = $this->checkOrderNotify($orderid);
        if(!$find){
            echo 'order_not_found'; exit;
        }

        //获取渠道信息
        $this->config = M("Channel")->where(array('code'=>$this->class))->find();

        //保存回调数据
        M("Order")->where(array("pay_orderid"=>$orderid))->save(array(

            "pay_orderid_rd"=>htmlspecialchars($p['tradeNo'])
        ));

        unset($p['sign']);

        $sign2 = $this->callbackDosign($p, $this->config['signkey']);
        if($sign !== $sign2){
            die('fail');
        }

        if($p['tradeStatus']!== '1'){
           exit("pail fail");
        }

        $find = M("Order")->where(array("pay_orderid"=>$orderid))->find();

        if(!$find){
            echo 'order_not_found'; exit;
        }

        $this->async($find['pay_orderid'],'success');
    }

    public function callBackUrl(){

        echo '处理成功'; exit;
    }
}